//
//  IntegralListVC.m
//  BXlive
//
//  Created by bxlive on 2017/5/18.
//  Copyright © 2017年 cat. All rights reserved.
//

#import "IntegralListVC.h"
#import "IntegralListCell.h"
#import "IntegralListModel.h"
#import "BaseWebVC.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import <SLDeveloperTools/SLDeveloperTools.h>
#import <SDWebImage/SDWebImage.h>
#import <SDAutoLayout/SDAutoLayout.h>

@interface IntegralListVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,assign)BOOL isResh;
@property (nonatomic,assign) NSInteger offset;
@property(nonatomic,strong)UIButton *profitBtn;
@property(nonatomic,strong)UIButton *numBtn;

@end

@implementation IntegralListVC

-(NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = NSLocalizedString(@"邀请列表", nil);
    _isResh = YES;
    [self setupTableview];
    [self createHeadView];
    [self createRessh];
    
}
-(void)createRessh{
    if (_invite_apply_url && _invite_apply_url.length) {
        UIButton *addBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 35, 40)];
        [addBtn setImage:CImage(@"flowRecord_add") forState:BtnNormal];
        addBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        [addBtn addTarget:self action:@selector(addAction) forControlEvents:BtnTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:addBtn];
    }
    
    
    [self.tableView addHeaderWithTarget:self action:@selector(TableDragWithDown)];
    [self.tableView headerBeginRefreshing];
}

- (void)addAction {
    BaseWebVC *webVC = [[BaseWebVC alloc]init];
    webVC.loadUrl = _invite_apply_url;
    [self.navigationController pushViewController:webVC animated:YES];
}

-(void)TableDragWithDown {
    _isResh = YES;
    self.offset = 0;
    [self loadData];
}

- (void)loadMoreData {
    _isResh = NO;
    self.offset = self.dataArray.count;
    [self loadData];
}


-(void)loadData{
    [[NewHttpRequestPort sharedNewHttpRequestPort] InviteGetList:@{@"offset":[NSString stringWithFormat:@"%ld",(long)self.offset]} Success:^(id responseObject) {
        [self.tableView headerEndRefreshing];
        if([responseObject[@"code"] integerValue] == 0) {
            if (self.isResh == YES) {
                [self.dataArray removeAllObjects];
                self.tableView.isNoMoreData = NO;
            }
            
            NSArray *dataArray = responseObject[@"data"];
            if (dataArray && dataArray.count) {
                for (NSDictionary *dict in responseObject[@"data"]) {
                    IntegralListModel *model = [IntegralListModel appInfoWithDict:dict];
                    [self.dataArray addObject:model];
                }
            } else {
                self.tableView.isNoMoreData = YES;
            }
            [self.tableView reloadData];
        } else{
            [BGProgressHUD showInfoWithMessage:[responseObject valueForKey:@"msg"]];
        }
        
        self.tableView.isRefresh = NO;
        self.tableView.isNoNetwork = NO;
    } Failure:^(NSError *error) {
        self.tableView.isRefresh = NO;
        self.tableView.isNoNetwork = !error.isNetWorkConnectionAvailable;
    }];

}
- (void)setupTableview {
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [self.view sd_addSubviews:@[self.tableView]];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.tableFooterView = [[UIView alloc]init];
    self.tableView.sd_layout.spaceToSuperView(UIEdgeInsetsMake(0, 0, 0, 0));
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 54;
}
- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    IntegralListCell *cell = [IntegralListCell  cellWithTableView:tableView];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.dataArray[indexPath.row];
    cell.backgroundColor = [UIColor clearColor];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGPoint point =  [scrollView.panGestureRecognizer translationInView:self.view];
    if (point.y > 0 ) {
        return;
    }
    if (scrollView.contentOffset.y <= 0) {
        return;
    }
    if (scrollView.contentOffset.y + scrollView.frame.size.height + kFooterRefreshSpace > scrollView.contentSize.height) {
        if (scrollView.isNoMoreData || scrollView.isNoNetwork) {
            return;
        }
        if (!scrollView.isRefresh) {
            scrollView.isRefresh = YES;
            [self loadMoreData];
        }
    }
}


-(void)createHeadView{
    
    UIView *header = [UIView new];
    // 由于tableviewHeaderView的特殊性，在使他高度自适应之前你最好先给它设置一个宽度
    header.width = [UIScreen mainScreen].bounds.size.width;
    header.backgroundColor = [UIColor clearColor];
    UIImageView *bgImage = [UIImageView new];
//    bgImage.image = [UIImage imageNamed:@"yqlb_banner"];
    UIView *bgView = [UIView new];
    bgView.backgroundColor = [UIColor clearColor];
    [header sd_addSubviews:@[bgImage,bgView]];
    
    bgImage.sd_layout.topSpaceToView(header, 0).leftSpaceToView(header, 0).rightSpaceToView(header, 0).heightIs(SCREEN_WIDTH*297.f/750.f);
    bgView.sd_layout.topSpaceToView(bgImage, -20).centerXEqualToView(header).widthIs(200).heightIs(40);
//    bgView.sd_cornerRadius = @(20);
    self.profitBtn = [UIButton new];
    self.profitBtn.titleLabel.font = CFont(13);
//    [self.profitBtn setImage:[UIImage imageNamed:@"ljsy"] forState:UIControlStateNormal];
    [self.profitBtn setImagePosition:0 spacing:5];
    [self.profitBtn setTitleColor:TextBrightestColor forState:UIControlStateNormal];
    self.numBtn = [UIButton new];
    self.numBtn.titleLabel.font = CFont(13);
//    [self.numBtn setImage:[UIImage imageNamed:@"yqhy"] forState:UIControlStateNormal];
    [self.numBtn setImagePosition:0 spacing:5];
    [self.numBtn setTitleColor:TextBrightestColor forState:UIControlStateNormal];
    UIView *bottomLine = [UIView new];
    bottomLine.backgroundColor = CHHCOLOR_D(0xebebeb);
    

    [bgView sd_addSubviews:@[self.numBtn,self.profitBtn,bottomLine]];
    self.numBtn.sd_layout.topSpaceToView(bgView, 0).leftSpaceToView(bgView , 0).widthIs(100).heightIs(40);
    bottomLine.sd_layout.topSpaceToView(bgView, 5).leftSpaceToView(self.numBtn, 0).bottomSpaceToView(bgView, 5).widthIs(0.7);
    self.profitBtn.sd_layout.topSpaceToView(bgView, 0).rightSpaceToView(bgView , 0).widthIs(100).heightIs(40);
    [header setupAutoHeightWithBottomView:bgView bottomMargin:10];
    [header layoutSubviews];
    self.tableView.tableHeaderView = header;
    
    [self.numBtn setTitle:self.num forState:UIControlStateNormal];
    [self.profitBtn setTitle:self.profit forState:UIControlStateNormal];
    
}

#pragma - mark DZNEmptyDataSetSource
- (UIView *)customViewForEmptyDataSet:(UIScrollView *)scrollView {
    if ([NewHttpManager isNetWorkConnectionAvailable]) {
        return nil;
    } else {
        WS(ws);
        BXNoNetworkView *noNetworkView = [[BXNoNetworkView alloc]initWithHeight:290];
        noNetworkView.needRefresh = ^{
            [ws TableDragWithDown];
        };
        return noNetworkView;
    }
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"空页面状态"];
    
}

- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *text = NSLocalizedString(@"这里还没有内容哦~", nil);
    NSMutableDictionary *attributes = [NSMutableDictionary new];
    NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
    paragraph.lineBreakMode = NSLineBreakByWordWrapping;
    paragraph.alignment = NSTextAlignmentCenter;
    [attributes setObject:[UIFont systemFontOfSize:17] forKey:NSFontAttributeName];
    [attributes setObject:MinorColor forKey:NSForegroundColorAttributeName];
    [attributes setValue:paragraph forKey:NSParagraphStyleAttributeName];
    NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:text attributes:attributes];
    return attributeString;
}


#pragma - mark DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}


@end
